package com.water.app.Controller.ws;

import cn.hutool.json.JSONUtil;
import com.water.app.Constant;
import com.water.app.PrivateChatMsg;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
class WebController {
    @Resource
    private SimpMessagingTemplate messagingTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    // 日期格式化工具（用于给消息添加发送时间，线程安全）
    private static final SimpleDateFormat SDF=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

    @MessageMapping("/chat/private")
    public void handlePrivateChat(PrivateChatMsg msg){
        msg.setDate(SDF.format(new Date()));
        String context = msg.getMsg();
        String date = msg.getDate();
        long sender = msg.getSender();
        long receiver = msg.getReceiver();
        long max = Math.max(sender, receiver);
        long min = Math.min(sender, receiver);
        String key=Constant.CHAT_PRIVATE + "user1:" + min + ":user2:" + max;
        stringRedisTemplate.opsForList().leftPushIfPresent(key,
                JSONUtil.toJsonStr(msg));
        stringRedisTemplate.expire(key,7, TimeUnit.DAYS);
        List<String> range = stringRedisTemplate.opsForList().range(key, -1, -1);
        if(range!=null&&range.contains("temp")){
            stringRedisTemplate.opsForList().rightPop(key);
        }
        messagingTemplate.convertAndSendToUser(String.valueOf(receiver),
                "/queue/chat/private",
                msg);

        messagingTemplate.convertAndSendToUser(String.valueOf(sender),
                "/queue/chat/private",
                msg);

        System.out.printf(
                "📩 私聊消息转发：发送者=%d → 接收者=%d，内容：%s，时间：%s%n",
                sender, receiver, context, date
        );
    }

}